<?php
/** 
 * 公益
 * Author:zhang
 *
 */

namespace Api\Controller;

class WelfareController extends ApiController{

	public function __construct(){
    	parent::__construct();
    	/** 测试不判断登录 modify by zhang 2016 start  **/
    	if (!I('mytest')) {
	        !api_login() && response(-94);
	        !passed_login() && response(-95);
	        !only_login() && response(-96);
    	}
    	/** 测试不判断登录 modify by zhang 2016 end **/
	}
    //首页
    function index(){
    	$m_welfare = M('Welfare');
    	$data = $m_welfare->field("id,title,price,time")->select();
    	foreach ($data as $key=>$val) {
    	    $data[$key]['time'] = date('Y-m-d', $val['time']);
    	    $data[$key]['hasMoney'] = M('welfare_list')->where('wid='.$val['id'])->sum('price');
        }
    	response(1,$data);
    }
    //添加公益活动
    function add(){
    	$m_welfare = M('Welfare');
    	$data = $m_welfare->create();
    	$data['time'] = NOW_TIME;
    	$result = $m_welfare->add($data);
    	$result ? response(1,$result):response(-9);
    }
    //捐款
    function donation(){
		params_exist(array('price','wid'));
		$uid = API_UID;
		$price = floatval(I('price',0));
		$wid = I('wid');
		if ($price <= 0) {
			response(-98);
		}

		$m_user = M('member');
		$user_amount = $m_user->where(array('uid'=>$uid))->getField('amount');
		if ($user_amount < $price) {
			response(-2,'余额不足');
		}

		$m_user -> startTrans();
		try{
			$r1 = $m_user->where(array('uid'=>$uid))->setDec('amount',$price);
            /* 添加资金流水记录 modify by liujb 20170208 start */
            addCapitalflow('捐款',"-".$price,$uid);
            /* 添加资金流水记录 modify by liujb 20170208 end */
			$data = array(
				'wid'	=>$wid,
				'uid'	=> $uid,
				'price'	=>$price,
                'time' => NOW_TIME
			);
			$r2 = M('Welfare_list')->add($data);
			if ($r1 && $r2) {
				$m_user->commit();
				response(1,"捐款成功");
			}else{
				$m_user->rollback();
				response(-2,"捐款失败");
			}
		}catch(Exception $e){
			$m_user->rollback();
			response(-2,"捐款失败");
		}
    }
    //我的捐款
    function myDonation(){
    	$data = M('Welfare_list')->alias('wl')->field('wl.price,w.title,wl.time,w.id')
    			->join("left join __WELFARE__ w on wl.wid=w.id")
    			->where(array('wl.uid'=>API_UID))
    			->order("wl.time desc")
    			->select();
    	foreach ($data as $key=>$val) {
    	    $data[$key]['time'] = date('Y-m-d', $val['time']);
        }
    	response(1,$data);
    }
    //公益详情
    function info(){
    	params_exist(array('id'));
    	$id = I('id');
    	$welfare_info = M('welfare')->find($id);
    	$welfare_info['count'] = M('Welfare_list')->where(array('wid'=>$id))->count();
    	$welfare_info['w_price'] = M('Welfare_list')->where(array('wid'=>$id))->sum('price');
    	response(1,$welfare_info);
    }
}